<template>
    <div class="person-position-container">
        <!-- 搜索框 -->
        <div class="search-container">
            <el-input v-model="searchName" placeholder="请输入姓名搜索" clearable @clear="handleSearchClear"
                @keyup.enter="handleSearch" style="width: 300px; margin-right: 10px"></el-input>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button type="success" @click="handleAdd">新增</el-button>
        </div>

        <!-- 数据表格 -->
        <el-table :data="tableData" border style="width: 100%" v-loading="loading" @row-click="handleRowClick">
            <el-table-column prop="personId" label="ID" width="80" v-if="false"></el-table-column>
            <el-table-column prop="personName" label="姓名" width="120" sortable></el-table-column>
            <el-table-column prop="positionTitles" label="职务">
                <template #default="{ row }">
                    <el-tag v-for="position in row.positionTitles" :key="position.positionId" style="margin-right: 5px">
                        {{ position }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="createdAt" label="创建时间" width="180" sortable></el-table-column>
            <el-table-column prop="updatedAt" label="更新时间" width="180" sortable></el-table-column>
            <el-table-column label="操作" width="180" fixed="right">
                <template #default="{ row }">
                    <el-button size="small" @click.stop="handleEdit(row)">编辑</el-button>
                    <el-button size="small" type="danger" @click.stop="handleDelete(row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :current-page="pagination.currentPage" :page-sizes="[10, 20, 50, 100]" :page-size="pagination.pageSize"
                layout="total, sizes, prev, pager, next, jumper" :total="pagination.total"></el-pagination>
        </div>

        <!-- 新增/编辑对话框 -->
        <el-dialog :title="dialogTitle" v-model="dialogVisible" width="50%" :close-on-click-modal="false">
            <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
                <el-form-item label="姓名" prop="personName">
                    <el-input v-model="form.personName"></el-input>
                </el-form-item>
                <el-form-item label="职务" prop="positionTitles">
                    <el-select v-model="form.positionTitles" multiple filterable allow-create default-first-option
                        placeholder="请选择或输入职务" style="width: 100%">
                        <el-option v-for="position in allPositions" :key="position.positionId" :label="position.title"
                            :value="position.positionId"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitForm">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
    searchPersonPosition,
    addPersonPosition,
    updatePersonPosition,
    deletePersonPosition,
    getAllPositions
} from '@/api/personPosition'

export default {
    name: 'PersonPositionListView',
    setup() {
        const tableData = ref([])
        const loading = ref(false)
        const searchName = ref('')
        const dialogVisible = ref(false)
        const dialogTitle = ref('新增')
        const form = ref({
            personId: null,
            personName: '',
            positionTitles: []
        })
        const formRef = ref(null)
        const allPositions = ref([])
        const pagination = ref({
            currentPage: 1,
            pageSize: 10,
            total: 0
        })

        const rules = {
            personName: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
            positionTitles: [{ required: true, message: '请至少选择一个职务', trigger: 'change' }]
        }

        // 获取数据
        const fetchData = async () => {
            try {
                loading.value = true
                const params = {
                    page: pagination.value.currentPage,
                    size: pagination.value.pageSize,
                    name: searchName.value
                }

                const response = await searchPersonPosition(params);
                tableData.value = response
                pagination.value.total = response.length || 0
            } catch (error) {
                // ElMessage.error('获取数据失败: ' + error.message)
            } finally {
                loading.value = false
            }
        }

        const fetchAllPositionData = async () => {
            try {
                const response = await getAllPositions();
                allPositions.value = response;
            } catch (error) {
                // ElMessage.error('获取职位数据失败: ' + error.message)
            } finally {
                loading.value = false
            }
        }

        // 搜索
        const handleSearch = () => {
            pagination.value.currentPage = 1
            fetchData()
        }

        // 清空搜索
        const handleSearchClear = () => {
            searchName.value = ''
            handleSearch()
        }

        // 新增
        const handleAdd = () => {
            dialogTitle.value = '新增'
            form.value = {
                personId: null,
                personName: '',
                positionTitles: []
            }
            dialogVisible.value = true
        }

        // 编辑
        const handleEdit = (row) => {
            dialogTitle.value = '编辑'
            form.value = {
                personId: row.personId,
                personName: row.personName,
                positionTitles: row.positionTitles
            }
            dialogVisible.value = true
        }

        // 删除
        const handleDelete = (row) => {
            ElMessageBox.confirm('确定要删除这条记录吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            })
                .then(async () => {
                    try {
                        await deletePersonPosition(row.personId)
                        ElMessage.success('删除成功')
                        fetchData()
                    } catch (error) {
                        ElMessage.error('删除失败: ' + error.message)
                    }
                })
                .catch(() => { })
        }

        // 行点击
        const handleRowClick = (row) => {
            console.log('Row clicked:', row)
            // 可以在这里实现行点击的逻辑，如查看详情等
        }

        // 分页大小改变
        const handleSizeChange = (val) => {
            pagination.value.pageSize = val
            fetchData()
        }

        // 当前页改变
        const handleCurrentChange = (val) => {
            pagination.value.currentPage = val
            fetchData()
        }

        // 提交表单
        const submitForm = async () => {
            try {
                await formRef.value.validate()
                console.log('提交参数', form.value)
                const requestData = {
                    personName: form.value.personName,
                    positionTitles: form.value.positionTitles.map(id => {
                        const position = allPositions.value.find(p => p.positionId === id)
                        return position ? position.title : id // 如果是新创建的职务，直接使用id作为title
                    })
                }

                if (form.value.personId) {
                    // 更新
                    await updatePersonPosition(form.value.personId, requestData)
                    ElMessage.success('更新成功')
                } else {
                    // 新增
                    await addPersonPosition(requestData)
                    ElMessage.success('新增成功')
                }

                dialogVisible.value = false
                fetchData()
            } catch (error) {
                if (error.name !== 'ValidationError') {
                    ElMessage.error('操作失败: ' + error.message)
                }
            }
        }

        // 初始化
        onMounted(() => {
            fetchData()
            fetchAllPositionData()
        })

        return {
            tableData,
            loading,
            searchName,
            dialogVisible,
            dialogTitle,
            form,
            formRef,
            allPositions,
            pagination,
            rules,
            handleSearch,
            handleSearchClear,
            handleAdd,
            handleEdit,
            handleDelete,
            handleRowClick,
            handleSizeChange,
            handleCurrentChange,
            submitForm
        }
    }
}
</script>

<style scoped>

.search-container {
    margin-bottom: 20px;
}

.pagination-container {
    margin-top: 20px;
    text-align: right;
}
</style>